package com.yutian.selfservice.service.impl;

import com.yutian.selfservice.service.ServiceApplyService;
import com.yutian.selfservice.support.domain.ServiceApply;
import com.yutian.selfservice.support.domain.ServiceApplyContact;
import com.yutian.selfservice.support.mapper.ServiceApplyContactMapper;
import com.yutian.selfservice.support.mapper.ServiceApplyMapper;
import com.yutian.selfservice.support.mapper.ServiceApplyMaterialMapper;
import com.yutian.selfservice.support.utils.Result;
import com.yutian.selfservice.support.utils.SnowflakeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

@Service
@Slf4j
public class ServiceApplyServiceImpl implements ServiceApplyService {
    @Autowired
    private ServiceApplyMapper serviceApplyMapper;
    @Autowired
    private ServiceApplyContactMapper serviceApplyContactMapper;
    @Autowired
    private ServiceApplyMaterialMapper serviceApplyMaterialMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result apply(ServiceApply serviceApply) {
        try {
            Long applyId = SnowflakeUtils.nextId();
            serviceApply.setId(applyId).setStatus(0).setUserId(0l);
            //申请
            serviceApplyMapper.insert(serviceApply);
            ServiceApplyContact serviceApplyContact = serviceApply.getServiceApplyContact();
            serviceApplyContact.setApplyId(applyId);
            //申请联系人
            serviceApplyContactMapper.insert(serviceApplyContact);
            //上传材料关联
            if (!CollectionUtils.isEmpty(serviceApply.getServiceApplyMaterials())) {
                serviceApply.getServiceApplyMaterials().forEach(x -> {
                    x.setId(SnowflakeUtils.nextId());
                    serviceApplyMaterialMapper.insert(x);
                });
            }
            return Result.success();
        } catch (Exception e) {
            log.error("服务申请失败", e);
            return Result.fail("服务申请失败");
        }
    }
}
